'''
Author: cw
Date: 2025-07-22
Description: ...
'''
import traceback
import xml.etree.ElementTree as ET

from fapi import ServiceError, logger
from modules import user_mgr
from utils.wx_util import build_text_response


async def parse_wechat_message(appid:str, xml_data: str):
    """
    处理微信服务器发来的消息
    解析XML消息
    """
    root = ET.fromstring(xml_data)
    # 获取消息基本信息
    source_id = root.find("ToUserName").text
    openid = root.find("FromUserName").text
    msg_type = root.find("MsgType").text
    _ = root.find("CreateTime").text

    # 消息内容处理
    try:
        if msg_type == "text":
            content = root.find("Content").text
            # 处理用户回复的答案
            if content == '菜单':
                return await user_mgr.menus(appid, openid, source_id)
            elif content == "测试":
                return await user_mgr.select_tests(appid, openid, source_id)
            elif content.isdigit():
                return await user_mgr.start_test(
                    appid=appid,
                    openid=openid,
                    source_id=source_id,
                    index=int(content),
                )
            elif content.startswith('云作图'):
                return await user_mgr.do_image_by_link(
                    appid=appid,
                    openid=openid,
                    content=content,
                    source_id=source_id
                )
            elif content.startswith('作图'):
                return await user_mgr.do_image(
                    appid=appid,
                    openid=openid,
                    content=content,
                    source_id=source_id
                )
            elif content.startswith('查看'):
                return await user_mgr.get_image(
                    appid=appid,
                    openid=openid,
                    content=content,
                    source_id=source_id
                )
            else:
                return await user_mgr.handle_user_answer(
                    appid=appid,
                    openid=openid,
                    content=content,
                    source_id=source_id
                )
        elif msg_type == "event":
            event = root.find("Event").text
            if event == "subscribe":
                # 处理用户关注事件
                return await user_mgr.handle_subscribe(appid, openid, source_id)
            elif event == "CLICK":
                # 处理菜单点击事件
                event_key = root.find("EventKey").text
                return await user_mgr.handle_menu_click(
                    appid=appid,
                    openid=openid,
                    event_key=event_key,
                    source_id=source_id
                )
    except ServiceError as e:
        logger.warning("处理消息时发生异常: %s", traceback.format_exc())
        return build_text_response(openid, source_id, e.msg)
    except Exception as ex:  # pylint: disable=broad-exception-caught
        logger.error("处理消息时发生错误: %s", ex)
        traceback.print_exc()
        return build_text_response(openid, source_id, "处理消息时发生错误，请稍后再试")
    # 默认回复
    return build_text_response(openid, source_id, "暂不支持该类型消息")
